﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Model;
using Model.Enum;
using UIDesign;
using Components;

namespace UIMarker
{
    public partial class FrmMain : Form
    {
        private string DELETE_SYS5A01_SQL = @"DELETE FROM Sys5a01 WHERE plistid = '{0}';";
        private string INSERT_SYS5A01_SQL = @"INSERT INTO Sys5a01(listid,plistid,orderid,colname,headcn,coltype,isquery,isshow,oname,fmt,editmode,controltype,maxlength,digits,defvalue,iskey,notnull,columnwidth,colspan,columnoption,columnparam,tp1,tp2,tp3,tp4,tp5,remark,tp6,tp7,tp8,tp9,tp10)
VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}','{20}','{21}','{22}','{23}','{24}','{25}','{26}','{27}','{28}','{29}','{30}','{31}');";
        private string UPDATE_SYS0A60_SQL = @"UPDATE Sys0a60 SET nowvalue = (SELECT max(a.listid) FROM Sys5a01 a WHERE a.plistid = '{0}')
WHERE nowvalue < (SELECT max(a.listid) FROM Sys5a01 a WHERE a.plistid = '{0}') AND sncode = 'sys5a01_listid'; ";

        private string action = "V"; //当前模式
        private Control lastClickControl = null;
        private bool isDown = false;
        private bool isDownToolBar = false;
        private string p_listid = "";
        private List<Sys5a01> delItems = null; //删除Item的集合
        private List<string> delAction = null; //删除的数据源集合

        public FrmMain()
        {
            InitializeComponent();
        }

        private void Init()
        {
            this.flwMain.Controls.Clear();
            this.gbToolBar.Enabled = false;
            MainHelp.Remove("");
        }

        //新增页面
        private void tspAdd_Click(object sender, EventArgs e)
        {
            txtcolsize.Enabled = true;
            txtcolsize.Clear();
            ctlname.Enabled = true;
            txtPageName.Enabled = true;
            txtPageName.Clear();
            txtPageName.Focus();
            this.gbToolBar.Enabled = true;

            this.flwMain.Controls.Clear();

            action = "A";
        }

        #region ToolBar
        private void lbToolItem_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            Control c = sender as Control;
            if (c == null)
            {
                return;
            }

            CreateControl(c.Tag.ToString(), null);
        }

        /// <summary>
        /// 工具栏中各个按钮的拖拽事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbToolBar_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDownToolBar)
            {
                Control c = sender as Control;
                if (c == null)
                {
                    return;
                }

                c.DoDragDrop(c.Tag, DragDropEffects.Copy);
            }
        }

        private void lbToolBar_MouseUp(object sender, MouseEventArgs e)
        {
            isDownToolBar = false;
        }

        private void lbToolBar_MouseDown(object sender, MouseEventArgs e)
        {
            isDownToolBar = true;
        }
        #endregion

        #region 生成的控件调用的方法
        void lb_MouseClick(object sender, MouseEventArgs e)
        {
            if (null != lastClickControl)
            {
                lastClickControl.BackColor = Color.Transparent;
            }

            Control c = (Control)sender;
            c.BackColor = Color.Yellow;
            lastClickControl = c;
            this.pgRight.SelectedObject = sender;
        }

        void lb_MouseUp(object sender, MouseEventArgs e)
        {
            isDown = false;
            isDownToolBar = false;
        }

        void lb_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDown)
            {
                ItemLabel tmp = (ItemLabel)sender;
                tmp.DoDragDrop(sender, DragDropEffects.Copy);
            }
        }

        void lb_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.All;
        }

        void lb_DragDrop(object sender, DragEventArgs e)
        {
            bool isMove = Form.IsKeyLocked(Keys.CapsLock); //开启大写，就是移动
            ItemLabel src = e.Data.GetData(typeof(ItemLabel)) as ItemLabel;
            Control tag = this.flwMain.GetChildAtPoint(this.flwMain.PointToClient(new Point(e.X, e.Y)));
            int sidx = this.flwMain.Controls.GetChildIndex(src, true); //原控件的序号
            int idx = this.flwMain.Controls.GetChildIndex(tag, true);
            this.flwMain.Controls.SetChildIndex(src, idx);
            src.Orderid = idx;

            if (isMove == false)
            {
                this.flwMain.Controls.SetChildIndex(tag, sidx);
                ItemLabel c = tag as ItemLabel;
                c.Orderid = sidx;
            }

            isDown = false;
            isDownToolBar = false;
        }

        void lb_MouseDown(object sender, MouseEventArgs e)
        {
            isDown = true;
        }
        #endregion

        #region 显示面板的方法
        private void flwMain_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.All;
        }

        private void flwMain_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(System.String)))
            {
                string s = e.Data.GetData(typeof(string)).ToString();
                CreateControl(s, null);
            }

            isDown = false;
            isDownToolBar = false;
        }
        #endregion

        /// <summary>
        /// 在Layout中创建一个控件
        /// </summary>
        /// <param name="tag">工具栏中tag的值</param>
        private void CreateControl(string tag, Sys5a01 tlayout)
        {
            ControlType ctype = (ControlType)Convert.ToInt32(tag); //控件类型

            ItemLabel lb = MainHelp.CreateControl(ctype);
            if (null != tlayout)
            {
                CommonUtil.GetInstance.CopyProperties(tlayout, lb, true, true);
            }

            lb.Controltype = ctype;
            lb.ControlStr = MainHelp.LIST[Convert.ToInt32(tag)];
            lb.Plistid = this.p_listid;
            lb.Text = (string.IsNullOrEmpty(lb.Headcn))
                    ? "未知列名" + (this.flwMain.Controls.Count + 1)
                    : lb.Headcn;
            lb.Orderid = this.flwMain.Controls.Count;
            lb.MouseClick += new MouseEventHandler(lb_MouseClick);
            lb.MouseDown += new MouseEventHandler(lb_MouseDown);
            lb.MouseMove += new MouseEventHandler(lb_MouseMove);
            lb.MouseUp += new MouseEventHandler(lb_MouseUp);
            lb.DragDrop += new DragEventHandler(lb_DragDrop);
            lb.DragEnter += new DragEventHandler(lb_DragEnter);
            lb.ContextMenuStrip = this.contextMenuStrip1;
            lb.Width = 300;
            this.flwMain.Controls.Add(lb);
        }

        private void 从现有表中提取ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmSelectField frm = new FrmSelectField("1");
            if (frm.ShowDialog() == DialogResult.OK)
            {
                List<Sys5a01> list = frm.GetSelectedRow();
                if (null == list)
                {
                    return;
                }

                foreach (Sys5a01 c in list)
                {
                    CreateControl(Convert.ToInt32(c.Controltype).ToString(), c);
                }
            }
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ItemLabel lb = this.contextMenuStrip1.SourceControl as ItemLabel;
            if (null == lb)
            {
                return;
            }

            Sys5a01 sys5a01 = null;
            //如果listid为空，则证明该控件是新增的，不记录到集合中
            if (!string.IsNullOrEmpty(lb.Listid))
            {
                if (null == delItems)
                {
                    delItems = new List<Sys5a01>();
                }
                sys5a01 = new Sys5a01();
                CommonUtil.GetInstance.CopyProperties(lb, sys5a01, true, true);
                delItems.Add(sys5a01);
            }

            if (lastClickControl == lb) //删除的是最后一次选中的
            {
                lastClickControl = null;
            }

            MainHelp.Remove(lb.Colname);
            this.flwMain.Controls.Remove(lb); //移除控件
        }

        private void tsBtn_Reset_Click(object sender, EventArgs e)
        {
            Init();
            LoadControl();
            delItems = null;
            if (0 != this.flwMain.Controls.Count)
                this.gbToolBar.Enabled = true;
        }

        private void tsbtnSelect_Click(object sender, EventArgs e)
        {
            FrmPageList pg = new FrmPageList("s");
            if (pg.ShowDialog() == DialogResult.OK)
            {
                Init(); //先初始化

                Sys5a00 sv = pg.GetSelectedValue();
                this.txtPageName.Text = sv.Pagename;
                p_listid = sv.Listid;
                this.ctlname.Text = sv.Ctlname;
                this.txtcolsize.Text = Validation.ToString(sv.Colsize);
                LoadControl(); //加载控件
                this.gbToolBar.Enabled = true;

                DataTable dtData = sys5a02Dal.GetList(p_listid);
                this.dgvSource.Rows.Clear();
                DataGridViewRow dgr = null;
                DataGridViewRow ndr = null;
                foreach (DataRow dr in dtData.Rows)
                {
                    dgr = new DataGridViewRow();
                    dgr.CreateCells(this.dgvSource);

                    dgvSource.Rows.Add(dgr);
                    ndr = dgvSource.Rows[dgvSource.Rows.Count - 1];
                    ndr.Cells["taction"].Value = dr["taction"];
                    ndr.Cells["mk"].Value = dr["mk"];
                    ndr.Cells["listid"].Value = dr["listid"];
                }

                this.gbToolBar.Enabled = true;
            }
        }

        private void LoadControl()
        {
            if (string.IsNullOrEmpty(this.p_listid)) return;
            //得到字段设计列表
            DataTable dt = sys5a01Dal.GetList(this.p_listid);

            List<Sys5a01> lst = Sys5a01.GetSys5a01ListByDataTable(dt);
            int i = -1;
            foreach (Sys5a01 sy in lst)
            {
                i = Array.IndexOf(MainHelp.SLIST, Convert.ToInt32(sy.Controltype).ToString());
                if (i == -1) continue;

                MainHelp.AddCnList(sy.Colname);
                CreateControl(i.ToString(), sy);
            }
        }

        private void tsbtnDelete_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.p_listid)) return;

            if (MessageBox.Show(this, "是否确认删除？", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                bool suc = sys5a00Dal.Delete(this.p_listid);
                if (!suc)
                {
                    MessageBox.Show("又出错啦！");
                }
                else
                {
                    MessageBox.Show("删除成功！");
                    this.flwMain.Controls.Clear();// 清除当前的控件
                }
            }
        }

        private void tsbtnCopy_Click(object sender, EventArgs e)
        {
            string pageName = txtPageName.Text;
            string ctls = ctlname.Text;
            if (string.IsNullOrEmpty(pageName))
            {
                MessageBox.Show("请输入页面名称！", "提示");
                txtPageName.Focus();
                return;
            }
            else if (string.IsNullOrEmpty(ctls))
            {
                MessageBox.Show("请选择控件！", "提示");
                ctlname.Focus();
                return;
            }
            FrmCopy frm = new FrmCopy(pageName, ctls, txtcolsize.Text, this.p_listid);
            frm.ShowDialog();
            if (frm.OpResult) //操作成功，刷新
            {
                tsBtn_Reset_Click(null, null);
                txtcolsize.Enabled = false;
                txtPageName.Enabled = false;
                ctlname.Enabled = false;
                this.action = "V";
            }
        }

        private void 新增数据源ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Sys5a02 newModel = new Sys5a02();
            newModel.Plistid = this.p_listid;
            FrmPageSource frm = new FrmPageSource(newModel);
            frm.ShowDialog();
            Sys5a02 model = frm.GetEditModel();
            if (model == null) return;

            DataGridViewRow dr = new DataGridViewRow();
            dr.CreateCells(this.dgvSource);
            dgvSource.Rows.Add(dr);

            DataGridViewRow lstRow = dgvSource.Rows[dgvSource.Rows.Count - 1];
            lstRow.Cells["taction"].Value = model.Action;
            lstRow.Cells["listid"].Tag = model;
        }

        private void ctxSourceLeft_Opening(object sender, CancelEventArgs e)
        {
            删除ToolStripMenuItem.Enabled = true;
            修改数据源ToolStripMenuItem.Enabled = true;

            if (this.dgvSource.SelectedCells.Count == 0
                || this.dgvSource.SelectedCells[0].RowIndex < 0)
            {
                删除ToolStripMenuItem.Enabled = false;
                修改数据源ToolStripMenuItem.Enabled = false;
            }
        }

        private void 修改数据源ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.dgvSource.SelectedCells.Count == 0
                || this.dgvSource.SelectedCells[0].RowIndex < 0) return;

            DataGridViewRow dr = this.dgvSource.Rows[this.dgvSource.SelectedCells[0].RowIndex];
            object listid = dr.Cells["listid"].Value;
            object addModel = dr.Cells["listid"].Tag;
            if (null == listid && addModel == null) return;

            Sys5a02 model = null;
            if (addModel != null && listid != null) //修改模式下，对已经修改过的数据进行修改
            {
                model = addModel as Sys5a02;
            }
            else if (listid != null) //修改情况下，第一次点入
            {
                model = new Sys5a02();
                model.Listid = listid.ToString();
            }
            else if (addModel != null) //新增模式点入 ,且是对已编辑过的数据再次编辑
            {
                model = addModel as Sys5a02;
            }
            else if (listid is Sys5a02)//新增模式第一次点入
            {
                model = new Sys5a02();
            }

            FrmPageSource frm = new FrmPageSource(model);
            frm.ShowDialog();

            Sys5a02 editmodel = frm.GetEditModel();
            if (null == editmodel) return;
            dr.Cells["taction"].Value = model.Action;
            dr.Cells["listid"].Tag = model;
        }

        private void 删除数据源ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.dgvSource.SelectedCells.Count == 0 || this.dgvSource.SelectedCells[0].RowIndex < 0) return;

            if (MessageBox.Show("是否删除数据源?", "提示", MessageBoxButtons.YesNo) != DialogResult.Yes) return;

            int rowIndex = this.dgvSource.SelectedCells[0].RowIndex;
            DataGridViewRow dr = this.dgvSource.Rows[rowIndex];
            if (!Validation.IsNull(dr.Cells["mk"].Value))
            {
                //如果是数据库已经存在的记录，先将数据源ID保存起来，待保存时，一起回写数据库
                if (delAction == null)
                {
                    delAction = new List<string>();
                }

                object listid = dr.Cells["listid"].Value;
                if (listid is string) delAction.Add(listid.ToString());
                else if (listid is Sys5a02) delAction.Add(((Sys5a02)listid).Listid);

                this.dgvSource.Rows.RemoveAt(rowIndex);
            }
        }

        //弹出框数据源
        private void bs1_Click(object sender, EventArgs e)
        {
            FrmPopSource frm = new FrmPopSource("1");
            frm.Show();
        }

        private void bs2_Click(object sender, EventArgs e)
        {
            FrmFunSource frm = new FrmFunSource("1");
            frm.Show();
        }

        private void tspCreateSQL_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.p_listid))
            {
                MessageBox.Show("非修改模式生成不了布局SQL!", "提示");
                return;
            }

            StringBuilder sb = new StringBuilder();
            //先删除之
            sb.Append(string.Format(DELETE_SYS5A01_SQL, this.p_listid));
            sb.AppendLine();

            ItemLabel item = null;
            foreach (Control c in this.flwMain.Controls)
            {
                item = c as ItemLabel;

                sb.AppendLine(string.Format(INSERT_SYS5A01_SQL,
                    item.Listid, item.Plistid, item.Orderid, item.Colname, item.Headcn, Convert.ToInt32(item.Coltype),
                    item.Isquery ? "Y" : "N",
                    item.Isshow ? "Y" : "N",
                    item.Oname, item.Fmt, item.Editmode, Convert.ToInt32(item.Controltype),
                    item.Maxlength, item.Digits, item.Defvalue,
                    item.Iskey ? "Y" : "N",
                    item.Notnull ? "Y" : "N",
                    item.Columnwidth, item.Colspan, item.Columnoption, item.Columnparam,
                    item.Tp1, item.Tp2, item.Tp3, item.Tp4, item.Tp5, item.Remark, item.Tp6,
                    item.Tp7, item.Tp8, item.Tp9, item.Tp10));
            }

            sb.AppendLine(string.Format(UPDATE_SYS0A60_SQL, this.p_listid));

            sb.AppendLine();
            Clipboard.SetDataObject(sb.ToString());
            MessageBox.Show("OK!", "提示");
        }

        private void 页面列表_Click(object sender, EventArgs e)
        {
            var frm = new FrmSys5a00Slt();
            frm.Show();
        }
    }
}
